// pages/course/search/search.js

let app = getApp();

Page({
  data: {
    url: '',
    pageNum: 1,
    pageSize: 10,
    userSearchRecords: [],
    pages: 0,
    isLoading: false,
    searchValue: '', // 搜索框内容
    searchResults: [], // 搜索结果
  },
//清空搜索历史
clearHistory() {
  // 获取用户 ID
  const userId = app.globalData.userInfo?.id;
  if (!userId) {
    wx.showToast({ title: '用户未登录', icon: 'none' });
    return;
  }

  wx.showModal({
    title: '确认清空？',
    content: '确定要清空所有搜索记录吗？',
    success: (res) => {
      if (res.confirm) {
        wx.request({
          url: this.data.url + 'userSearchRecord/clear?userId=' + encodeURIComponent(userId), 
          method: 'DELETE', 
          data: {
            userId: userId
          },
          success: (delRes) => {
            if (delRes.statusCode === 200 && delRes.data.code === 200) {
              this.setData({
                userSearchRecords: []
              });
              wx.showToast({ title: '已清空', icon: 'success' });
            } else {
              wx.showToast({ 
                title: delRes.data?.msg || '删除失败', 
                icon: 'none' 
              });
            }
          },
          fail: (err) => {
            console.error('【删除搜索记录失败】', err);
            wx.showToast({ 
              title: '网络错误', 
              icon: 'none' 
            });
          }
        });
      }
    }
  });
},
  //跳转详情页
  gotoCourseDetail(e){
    const courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/course/zxkc/kcxq/kcxq?id=${courseId}`,
    })
  },
  onInput(e) {
    const value = e.detail.value;
    this.setData({
      searchValue: value
    });

    // 如果有输入内容，执行搜索
    if (value.trim() !== '') {
      this.searchCourses(value);
    } else {
      // 清空搜索结果
      this.setData({
        searchResults: []
      });
    }
  },

  // 执行搜索请求
searchCourses(keyword) {
  wx.showLoading({ title: '搜索中...' });
  console.log('搜索关键词:', keyword);

  wx.request({
    url: this.data.url + 'controller/page',
    method: 'GET',
    data: {
      courseName: keyword,
      pageNum: 1,
      pageSize: 10
    },
    success: (resp) => {
      console.log('【搜索结果】完整响应:', resp);
      
      const responseData = resp.data;
      if (resp.statusCode === 200 && responseData && responseData.data) {
        const results = responseData.data.list || [];
        this.setData({
          searchResults: results
        });
        
        if (results.length === 0) {
          wx.showToast({ title: '未找到相关课程', icon: 'none' });
        }
      } else {
        this.setData({ searchResults: [] });
        wx.showToast({ 
          title: responseData?.msg || '请求失败', 
          icon: 'none' 
        });
      }
      const userId = app.globalData.userInfo?.id;
      if (!userId) {
        console.warn('用户未登录，无法保存搜索记录');
        return;
      }
      
      // wx.request({
      //   url: this.data.url + 'userSearchRecord' + userId,
      //   method: 'POST',
      //   data: {
      //     content: keyword,
      //     userId:userId 
      //   },
      //   success: (saveResp) => {
      //     console.log('【搜索记录保存成功】', saveResp);
      //   },
      //   fail: (err) => {
      //     console.error('【搜索记录保存失败】', err);
      //   }
      // });
      // 先查询是否已有该记录
      wx.request({
        url: this.data.url + 'userSearchRecord/user/' + userId,
        method: 'GET',
        success: (queryResp) => {
          if (queryResp.statusCode === 200 && Array.isArray(queryResp.data?.data)) {
            const allRecords = queryResp.data.data;
            const exists = allRecords.some(record => record.content === keyword);

            if (!exists) {
              // 不存在 → 保存到数据库
              this.createSearchRecord(keyword, userId);
            } else {
              // 已存在 → 不保存，但前端置顶
              this.updateFrontendRecords(keyword);
            }
          } else {
            // 查询失败 → 保守保存
            this.createSearchRecord(keyword, userId);
          }
        },
        fail: (err) => {
          console.error('【查询搜索记录失败】', err);
          this.createSearchRecord(keyword, userId);
        }
      });
    },
    fail: (err) => {
      console.error('请求失败:', err);
      wx.showToast({ title: '网络错误', icon: 'none' });
    },
    complete: () => {
      wx.hideLoading();
    }
  });
},
  // 创建搜索记录（仅当数据库中不存在时）
  createSearchRecord(keyword, userId) {
    wx.request({
      url: this.data.url + 'userSearchRecord',
      method: 'POST',
      data: { content: keyword, userId: userId },
      success: (saveResp) => {
        console.log('【搜索记录保存成功】', saveResp);
        // 保存成功后，前端更新（去重 + 置顶）
        this.updateFrontendRecords(keyword);
      },
      fail: (err) => {
        console.error('【搜索记录保存失败】', err);
      }
    });
  },

  // 更新前端历史记录（去重 + 置顶）
  updateFrontendRecords(keyword) {
    const currentRecords = this.data.userSearchRecords;
    const filtered = currentRecords.filter(record => record.content !== keyword);
    const newRecords = [{ content: keyword }, ...filtered];
    this.setData({ userSearchRecords: newRecords });
  },

  // 点击历史记录，触发搜索
  onHistoryClick(e) {
    const content = e.currentTarget.dataset.content;
    this.setData({
      searchValue: content
    });
    this.searchCourses(content);
  },

  getUserSearchRecord() {
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      console.warn('用户未登录，无法加载搜索记录');
      return;
    }
    wx.showLoading({ title: '加载中...' });
    this.setData({ isLoading: true });
    wx.request({
      url: this.data.url + 'userSearchRecord/user/' + userId,
      method: 'GET',
      data: {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
        userId: userId
      },
      success: (resp) => {
        console.log('【搜索记录】接口返回：', resp);
        const newList = resp.data?.data || [];
        this.setData({
          userSearchRecords: [...this.data.userSearchRecords, ...newList],
          pages: resp.data?.pages || 1
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },

  onLoad() {
    this.setData({ url: app.globalData.url });
    this.getUserSearchRecord();
  },

  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      userSearchRecords: [],
      pages: 0
    });
    this.getUserSearchRecord();
  },

  onReachBottom() {
    if (this.data.isLoading) return;

    this.setData({ pageNum: this.data.pageNum + 1 });

    if (this.data.pageNum > this.data.pages) {
      wx.showToast({ title: '已经到底了~', icon: 'none' });
      return;
    }
    this.getUserSearchRecord();
  }
});